<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace app\account\admin;

use app\common\builder\ZBuilder;
use app\admin\controller\Admin;
use app\user\model\User as UserModel;
use app\user\model\Role as RoleModel;
use app\pack\model\Pack as PackModel;
use app\pack\model\PackUser as PackUserModel;
use util\Tree;
use think\Db;

/**
 * 账号管理
 * @package app\admin\controller
 */
class Index extends Admin{
    public function index($type = '0')
    {
        $map = $this->getMap();
        $role = session('user_auth.role');
        $pid = session('user_auth.uid');
        if($role!=1){
            $map['pid'] = $pid;
        }
        $map['is_delete'] = 0;
        $pidUser= UserModel::where(array('id' =>$pid))->field('is_son,account_num,son_num')->find(); 
        if($role==4){
            $type=1;    
        }
        if($role==3 && $pidUser['is_son']==0){
            $type=1;
        }
        $map['type'] = $type;
        // 排序
        $order = $this->getOrder('create_time desc');
        // 数据列表
        $data_list = UserModel::where($map)->order($order)->paginate();
        // 分页数据
        $page = $data_list->render();
        // 绑定套餐
        // $btn_access = [
        //     'title' => '套餐',
        //     'icon'  => 'fa fa-fw fa-key',
        //     'href'  => url('pack', ['uid' => '__id__'])
        // ];
        $list_tab = [
            ['title' => '代理商', 'url' => url('index', ['type' => '0'])],
            ['title' => '普通账号', 'url' => url('index', ['type' => '1'])],
        ];   

        switch ($role) {
            case '1':
             $rolelist = array(
              2 => '运营',
              3 => '代理商',
              4 => '子代理商', 
              5=> '普通账号'
            );   
            break;
            case '2':
            $list_tab = [
                ['title' => '代理商', 'url' => url('index', ['type' => '0'])],
            ]; 
            break;
            case '3':
            $pidUser= UserModel::where(array('id' =>$pid))->field('is_son,account_num,son_num')->find(); 
            if($pidUser['is_son']==0){
               $list_tab = [
                    ['title' => '普通账号', 'url' => url('index', ['type' => '1'])],
                ];   
            }
                break;
            case '4':
             $rolelist = array(
              5=> '普通账号'
            );     
             $list_tab = [
                ['title' => '普通账号', 'url' => url('index', ['type' => '1'])],
            ]; 
                break;
            default:
                break;
        }
        // 统计信息
        $CountMessage =  $this->CountMessage();
        return ZBuilder::make('table')
            ->setPageTitle('账号管理') // 设置页面标题
            ->setTableName('admin_user') // 设置数据表名
            ->setTabNav($list_tab,$type)
            // ->addTopSelect('role', '全部',$rolelist)
            ->setPageTips($CountMessage, 'info')
            ->setSearch(['id' => 'ID', 'username' => '用户名', 'email' => '邮箱']) // 设置搜索参数
            ->addColumns([ // 批量添加数据列
                ['id', 'ID'],
                ['username', '用户名', 'text'],
                ['nickname', '昵称', 'text'],
                ['email', '邮箱','text'],
                ['mobile', '手机号','text'],
                ['create_time', '创建时间','datetime'],
                ['role', '角色', 'status', '', [1 => '超管:danger',2 => '运营:warning',3 => '代理商:primary', 4 => '子代理商:info', 5=> '普通账号:success']],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add,delete') // 批量添加顶部按钮
            // ->addRightButton('custom', $btn_access) // 添加授权按钮
            ->addRightButtons('edit,delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染模板
    }
    // 代理商 账号统计
    public function CountMessage()
    {
        $role = session('user_auth.role');
        $pid = session('user_auth.uid');
        $pidUser= UserModel::where(array('id' =>$pid))->field('is_son,account_num,son_num')->find(); 
        $accountCount= UserModel::where(array('pid' =>$pid,'role' =>5,'is_delete'=>0))->count(); 
        $agentCount= UserModel::where(array('pid' =>$pid,'role' =>['neq',5],'is_delete'=>0))->count(); 
        switch ($role) {
            case '2':
                $CountMessage = '代理商已创建'.$agentCount.'个<br>';
                break;
            case '3':
                if($pidUser['is_son']==1){
                    $agenttotal = $pidUser['son_num']-$agentCount;
                    $total = $pidUser['account_num']-$accountCount;
                   $CountMessage = '子代理商可创建：'.$agenttotal.'个,目前已创建'.$agentCount.'个<br>普通账号可创建：'.$total.'个,目前已创建'.$accountCount.'个'; 
               }else{
                    $total = $pidUser['account_num']-$accountCount;
                    $CountMessage = '普通账号可创建：'.$total.'个,目前已创建'.$accountCount.'个';
               }
                break;
            case '4':
                $total = $pidUser['account_num']-$accountCount;
                $CountMessage = '普通账号可创建：'.$total.'个,目前已创建'.$accountCount.'个';
                break;
            default:
                $CountMessage = '超管可查看所有账号信息';
                break;
        }
        return $CountMessage;
    }
    /**
     * 添加账号
     * @return mixed
     */
    public function add()
    {
        // 保存数据
        $role = session('user_auth.role');
        $pid = session('user_auth.uid');
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['username'] = addslashes($data['username']);
            $data['nickname'] = addslashes($data['nickname']);
            $data['type'] = 0;
            // 创建普通账号
            $agent= UserModel::where('id', $pid)->field('username,account_num,son_num')->find();
            if(empty($data['role'])){
                $this->error('请选择角色');
            }
            if($data['role']==5){
                $showcount= UserModel::where(array('pid' =>$pid,'role' =>5,'is_delete'=>0))->count();
                if($showcount>=$agent['account_num']){
                    $this->error('创建账号达到上限');
                }
                $data['type'] = 1;
                // 当创建普通账号，用户名为【代理商-数量】
                $account= UserModel::where(array('pid' =>$pid,'role' =>5,'is_delete'=>0))->field('fin_user')->order('id desc')->find();
                if(empty($account['fin_user'])){
                    $data['fin_user'] = $agent['username'].'_1';    
                }else{
                    $num= UserModel::where(array('pid' =>$pid,'role' =>5))->count();
                    $number = $num+1; 
                    $data['fin_user'] =  $agent['username'].'_'.$number;
                }
                $time = time(); //当前时间戳
                $data['start_time'] = date('Y-m-d H:i:s',time());
                if($data['is_give']==1){
                    $data['end_time'] = date('Y-m-d H:i:s',strtotime("+1 year +15 day"));    
                }else{
                    $data['end_time'] = date('Y-m-d H:i:s',strtotime("+1 year"));
                }
            }
            // 验证
            $result = $this->validate($data, 'User');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            // 创建子代理商
            if($data['role']==4){
                $son_agent= UserModel::where(array('pid' =>$pid,'role' =>4,'is_delete'=>0))->count();
                if($agent['son_num']==$son_agent){
                    $this->error('子代理商创建达到上限');
                }
            }
            if($data['role']==5){
                // 第三方平台开通账号
                $third = $this->thirdUser($data);
                $data['third'] = $third['uid'];
                $data['salt'] = $third['salt'];
            }
            $data['pid'] = $pid;
            $data['is_delete'] = 0;
            if ($user = UserModel::create($data)) {
                // 记录行为
                action_log('user_add', 'admin_user', $user['id'], UID);
                $this->success('新增成功', url('index'));
            } else {
                $this->error('新增失败');
            }
        }
        // 当前角色判断
        $new = $this->roleSelect();
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['radio', 'role', '开通角色', '', $new, '', '', '', 'active'],
                ['text', 'username', '用户名', '必填，可由英文字母、数字组成'],
                ['text', 'nickname', '昵称', '可以是中文'],
                ['text', 'mobile', '手机号'],
                ['text', 'email', '邮箱', ''],
                ['text','short','简称','必填，由公司名字首拼组成'],
                ['password', 'password', '密码', '必填，8-20位'],
                ['image', 'avatar', '头像'],
                ['text', 'account_num', '账号数量','默认数量为1','1'],
                ['radio', 'is_son', '是否具有开通子代理权限', '', ['不具有', '具有'], 0],
                ['text', 'son_num', '子代理个数'],
                ['static', 'titm12','套餐时间','','365天'],
                ['radio', 'is_give', '是否赠送15天', '', ['不赠送', '赠送'], 1],
                ['radio', 'status', '状态', '', ['禁用', '启用'], 1],
            ])
            ->setTrigger('role', 3, 'is_son')
            ->setTrigger('is_son', 1, 'son_num')
            ->setTrigger('role', '3,4', 'account_num')
            ->setTrigger('role', '5', 'titm12,is_give')
            ->layout([
                'username'      => 5,
                'nickname'      => 5,
                'short'         => 5,
                'password'      => 5,
                'mobile'        => 5,
                'email'         => 5,
                'type'          => 5,
                'account_num'   => 5,
                'son_num'       => 3,
                'is_son'        => 2,
                'titm12'        => 5,
                'is_give'       => 5,
            ])
            ->fetch();
    }
    // 角色选择
    public function roleSelect()
    {
        $role = session('user_auth.role');
        $pid = session('user_auth.uid');
        $role_map  = array();
        switch ($role) {
                case '2':
                    $role_map['id'] = ['=',3];
                    $type = array(0 =>'云平台');
                    break;
                case '3':
                    $agent= UserModel::where('id', $pid)->field('is_son')->find();
                    if($agent['is_son']){
                        $role_map['id'] = ['>',3];     
                    }else{
                        $role_map['id'] = ['=',5];
                    }
                    $type = array(0 =>'云平台',1 =>'人人商城');
                    break;
                case '4':
                    $role_map['id'] = ['=',5];
                    $type = array(0 =>'云平台',1 =>'人人商城');
                    break;
                default:
                    $type = array(0 =>'云平台',1 =>'人人商城');
                    break;
        }
        $roleList = RoleModel::where($role_map)->select();
        $new = [];
            foreach ($roleList as $k =>$v) {
            $new[$v['id']] = $v['name'];
        }
        return $new;
    }
    /**
     * 编辑
     * @param null $id 用户id
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     */
    public function edit($id = null)
    {
        if ($id === null) $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['username'] = addslashes($data['username']);
            $data['nickname'] = addslashes($data['nickname']);
            // 禁止修改超级管理员的角色和状态
            if ($data['id'] == 1 && $data['role'] != 1) {
                $this->error('禁止修改超级管理员角色');
            }
            // 禁止修改超级管理员的状态
            if ($data['id'] == 1 && $data['status'] != 1) {
                $this->error('禁止修改超级管理员状态');
            }
            // 验证
            $result = $this->validate($data, 'User.save');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            // 如果没有填写密码，则不更新密码
            if ($data['password'] == '') {
                unset($data['password']);
            }
            if ($user = UserModel::update($data)) {
                // 记录行为
                action_log('user_edit', 'admin_user', $user['id'], UID, get_nickname($user['id']));
                $this->success('编辑成功',url('index'));
            } else {
                $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = UserModel::where('id', $id)->field('password', true)->find();
        $new = $this->roleSelect();
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'id'],
                ['radio', 'role', '开通角色', '', $new, '', '', '', 'active'],
                ['text', 'username', '用户名', '必填，可由英文字母、数字组成'],
                ['text', 'nickname', '昵称', '可以是中文'],
                ['text', 'mobile', '手机号'],
                ['text', 'email', '邮箱', ''],
                ['text','short','简称','必填，由公司名字首拼组成'],
                ['password', 'password', '密码', ''],
                ['image', 'avatar', '头像'],
                ['text', 'account_num', '账号数量','默认数量为1','1'],
                ['radio', 'is_son', '是否具有开通子代理权限', '', ['不具有', '具有'], 0],
                ['text', 'son_num', '子代理个数'],
                ['radio', 'status', '状态', '', ['禁用', '启用'], 1],
            ])
            ->setTrigger('role', 3, 'is_son')
            ->setTrigger('is_son', 1, 'son_num')
            ->setTrigger('role', '3,4', 'account_num')
            ->setTrigger('role', '5', 'start_time')
            ->layout([
                'username'      => 5,
                'nickname'      => 5,
                'short'         => 5,
                'password'      => 5,
                'mobile'        => 5,
                'email'         => 5,
                'type'          => 5,
                'account_num'   => 5,
                'son_num'       => 3,
                'is_son'        => 2,
                'titm12'        => 5,
                'is_give'       => 5,
             
            ])
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }
    /**
     * 删除用户
     * @param array $record 行为日志
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     */
    public function delete($record = [])
    {
        $param = $this->request->param();
        $ids = $param['ids'];
        $where['id'] = $ids;
        if (is_array($ids)) {
            $where['id'] = array('in', $ids);
        }
        $data['is_delete'] = 1;
        $result = UserModel::where($where)->update($data);
        if ($result) {
            $this->success('删除成功', url('index'));
        } else {
            $this->error('删除失败');
        }
     }
    // 绑定套餐
    public function pack()
    {
      // 提交数据
      if ($this->request->isPost()) {
         $data = $this->request->post();
         $result =  PackUserModel::update($data);
          if ($result) {
               $this->success('绑定成功', url('index'));
            } else {
                $this->error('绑定失败');
            }
      }
      // 绑定套餐展示
      $param = $this->request->param();
      $uid = $param['uid'];
      $packUser =  DB::name('pack_user')->where(['uid' =>$uid])->find();
      if(empty($packUser)){
        $data['uid'] = $uid;
        DB::name('pack_user')->insert($data);
      }

      $packUser =  PackUserModel::where(['uid' =>$uid])->find();
      // 套餐列表
      $data_list = PackModel::where(['is_delete' =>0])->select();
        // 前端显示套餐
        $new = [];
      foreach ($data_list as $k =>$v) {
        $new[$v['id']] = $v['title'];
      }
       $role = session('user_auth.role');
      if($role!=1 && $role!=2){
            $auth_uid = session('user_auth.uid');
            $authUser = PackUserModel::where(array('uid' =>$auth_uid))->find();
            $pack = $authUser['pack'];
            foreach ($new as $k => $v) {
                if(!in_array($k,$pack)){
                    unset($new[$k]);
                }
            }
        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('绑定套餐') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'id'],
                ['checkbox', 'pack', '绑定套餐', '', $new, '', '', '', 'active'],
            ])
            ->setFormData($packUser) // 设置表单数据
            ->fetch();
      
    }
    // 请求第三方接口
    public function thirdUser($data){
        $type = $data['type'];
        switch ($type) {
            case 0:
                return;
                break;
            case 1:
                $result = $this->shopTwo($data);
                return $result;
                break;
            case 2:
            
                break;
            default:
               
                break;
        }
    }
    public function shopTwo($data){

        $params['username'] = $data['username'];
        $params['password'] = $data['password'];
        $params['nickname'] = $data['nickname'];
        $params['realname'] = $data['nickname'];
        $params['end_time'] = $data['end_time'];
        $opts = [
            CURLOPT_TIMEOUT        => 20,
            CURLOPT_RETURNTRANSFER => true,
            // CURLOPT_URL            => 'http://zje.twothink.com/web/index.php?c=api&a=register',
            CURLOPT_URL            => 'https://popular.vdongchina.com/web/index.php?c=api&a=register',
            CURLOPT_USERAGENT      => $_SERVER['HTTP_USER_AGENT'],
            CURLOPT_POST           => 1,
            CURLOPT_POSTFIELDS     => $params
        ];

        // 初始化并执行curl请求
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $result  = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($result, true);
        if ($result['code']==0) {
            return $result['data'];
        } else {
            $this->error($result['message']);
        }
        
    }

   
}
